import { Component, OnInit } from '@angular/core';
import'rxjs/add/operator/debounceTime';
import'rxjs/add/operator/distinctUntilChanged';
import { FormBuilder, FormGroup, Validators,FormControl } from '@angular/forms';
import { UserLogin } from './shared/user-login.model';
import { UserLoginService } from './shared/user-login.service';
import { flyInOut } from "../../utils/anim";
import { User } from "../share/user.model";
import { userService } from "../share/user.service";

@Component({
	selector: 'user-login',
	templateUrl: 'user-login.component.html',
	providers: [UserLoginService],
	animations: [
		flyInOut
	],
	styleUrls: ["user-login.component.scss"],
	
})

export class UserLoginComponent implements OnInit {
	loginForm: FormGroup;
	loginCor:FormControl;
	user: User = new User();
	userlogin: UserLogin = new UserLogin();
	constructor(private userLoginService: UserLoginService,
		private UserService: userService,
		private fb: FormBuilder
	) {

	}
	public formErrors = {
		'email': '',
		'password': ''
	};
	//maxlength小写
	validationMessages = {
		'email': {
			'required': '邮箱必须输入。',
			'pattern': '请输入正确的邮箱地址。'
		},
		'password': {
			'required': '密码必须输入。',
			'minlength': '密码至少要8位。',
			'maxlength': '最多12位。',
		}
	};
	ngOnInit() {
		this.bulidFrom();
	}
	// 创建驱动表单
	bulidFrom() {
		// 用FormBuilder工厂创建动态表单添加验证 
		// ngFormControl命令 
		this.loginForm = this.fb.group(
			{
				email: [this.user.email, [Validators.required, Validators.pattern("^[A-Za-zd]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$")]],
				password: [this.user.password, [Validators.maxLength(12), Validators.required, Validators.minLength(8)]]
			}
		);
		// this.loginForm.controls['email'].valueChanges.debounceTime(4000); 获取某个controls
		//debounceTime防抖动distinctUntilKeyChanged去除连续相同key的值 distinctUntilChanged去除连续重复的值
		this.loginForm.valueChanges.debounceTime(400).distinctUntilChanged().subscribe(data => this.onValueChanged());
		this.onValueChanged();
	}
	onValueChanged(data?: any) {
		if (!this.loginForm) { return; }
		//得到当前表单
		const form = this.loginForm;
		for (const field in this.formErrors) {
			this.formErrors[field] = '';
			 //取到表单字段
			const control = form.get(field);
			if (control && control.dirty && !control.valid) {
				//取出错误信息
				const messages = this.validationMessages[field];
				for (const key in control.errors) {
					this.formErrors[field] += messages[key] + ' ';
				}
			}
		}
	}
	login() {
		if (this.loginForm.valid) {
			this.userLoginService.login(this.user).subscribe((res) => {
				console.log("登录成功");
				this.user.id = 1;
				console.log(this.user);
			}, err => {
				console.log("访问出错");
				this.user.id = 1;
				console.log(this.user);
				this.UserService.setUser(this.user);
			}
			);
		}
	}

}